/*
 * @Author: your name
 * @Date: 2021-02-22 16:12:54
 * @LastEditTime: 2021-02-22 22:12:26
 * @LastEditors: Please set LastEditors
 * @Description: 深/浅拷贝
 * @FilePath: \relearnJS\interview\deepClone.js
 */

/*
    浅拷贝是指将一个对象的属性值复制到另一个对象，若有的属性为引用类型，那么会将这个引用类型的地址复制给那个对象，然后两个对象都有对同一个引用类型的引用

*/

function shallowClone(target) {
    // 先进行非空和是否是引用类型判断
    if (!target || typeof target !== 'object') return
    let cloneObject = Array.isArray(target) ? [] : {}
    for (let key in target) {
        if (target.hasOwnProperty(key)) {
            cloneObject[key] = target[key]
        }
    }
    return cloneObject
}

function deepClone(target) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {}
        for (const key in target) {
            cloneTarget[key] = deepClone(target[key])
        }
        return cloneTarget
    } else {
        return target
    }
}

const test = {
    field1: 1,
    field2: undefined,
    field3: 'tom',
    field4: {
        child: 'child',
        child2: {
            child2: 'child2'
        }
    }
}
//! 循环引用 递归进入死循环，导致栈内存溢出
// test.test = test
console.log(deepClone(test) === test)
console.log(Object.assign(test) === shallowClone(test))